/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>Project: app2022 - T15
 * <p>Powered by webrx On 2022-02-07 11:39:12
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T15 {
    int num = 50;
    //true 代表公平锁
    Lock lock = new ReentrantLock(true);

    public T15() {
    }

    public T15(int num) {
        this.num = num;
    }

    public static void main(String[] args) {
        var t = new T15(10);
        new Thread(t::test, "文化路").start();
        new Thread(t::test, "东风路").start();
        new Thread(t::test, "瑞达路").start();
        new Thread(t::test, "科学大道").start();
        new Thread(t::test, "南阳路").start();
    }

    void test() {
        String t = Thread.currentThread().getName();
        while (this.num >= 1) {
            lock.lock();
            this.num--;
            System.out.printf("%s : %d%n", t, this.num);
            try {
                TimeUnit.SECONDS.sleep(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (this.num <= 0) {
                break;
            }
            lock.unlock();
        }
    }
}
